<template>
  <pageHeader
    title="配置生产物料"
    :breadCrumb="['工厂建模', '生产BOM管理', '生产BOM管理']"
    :show-back="true"
  >
    <template #footer>
      <a-space :size="20">
        <a-button @click="router.back()">取消</a-button>
        <a-button type="primary" @click="handleOk">保存</a-button>
      </a-space>
    </template>
    <a-spin :loading="loading" class="cantainer">
      <div class="tab">产品信息</div>
      <a-form :model="formData" ref="refForm" auto-label-width class="form">
        <a-row :gutter="15">
          <a-col :span="12">
            <a-form-item label="关联产品">
              <ProductChoice disabled ref="refProductChoice" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="产品编码">
              <a-input :model-value="formData.management?.number" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="规格型号">
              <a-input :model-value="formData.management?.spec" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="基本单位">
              <a-input
                :model-value="formData.management?.unitData?.name"
                disabled
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div
        class="tab"
        style="margin-top: 20px; display: flex; justify-content: space-between"
      >
        <div>产品BOM版本与信息</div>
      </div>

      <a-table :data="productBomList" :pagination="false">
        <template #columns>
          <a-table-column
            v-for="header in [
              { code: 'bomCode', name: 'BOM编码', width: 200 },
              { code: 'bomName', name: 'BOM名称', width: 200 },
              { name: '产品编码' },
              { name: '产品名称' },
              { name: '规格型号' },
              { name: '基本单位' },
              { name: '状态' },
            ]"
            :key="header.name"
            :width="header.width || 200"
            :title="header.name"
            :data-index="header.code"
            align="center"
          >
            <template #cell="{ record }" v-if="!header.code">
              <template v-if="header.name === '状态'">
                <a-typography-text
                  type="success"
                  v-if="record.historyState === 1"
                >
                  启用
                </a-typography-text>
                <a-typography-text
                  type="danger"
                  v-if="record.historyState === 2"
                >
                  停用
                </a-typography-text>
              </template>
              <template v-if="header.name === '产品编码'">
                {{ record.management?.number }}
              </template>
              <template v-if="header.name === '产品名称'">
                {{ record.management?.name }}
              </template>
              <template v-if="header.name === '规格型号'">
                {{ record.management?.spec }}
              </template>
              <template v-if="header.name === '基本单位'">
                {{ record.management?.unitData?.name }}
              </template>
            </template>
          </a-table-column>
          <a-table-column
            :width="120"
            fixed="right"
            title="启用版本"
            align="center"
          >
            <!-- <template #cell="{ record }">
              <a-space>
                <a-switch
                  @click="switchClick(record)"
                  :model-value="record.historyState"
                  :checked-value="1"
                  :unchecked-value="2"
                />
              </a-space>
            </template> -->
          </a-table-column>
          <a-table-column
            :width="120"
            fixed="right"
            title="启用版本"
            align="center"
          >
            <template #cell="{ record }">
              <a-space>
                <a-switch
                  @click="switchBomClick(record)"
                  :model-value="record.historyState"
                  :checked-value="1"
                  :unchecked-value="2"
                />
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <a-form
        :model="formData"
        ref="refForm"
        auto-label-width
        class="form"
        style="margin-top: 20px"
      >
        <a-row :gutter="15">
          <a-col :span="12">
            <a-form-item label="产品BOM编码">
              <a-input
                placeholder="无需输入，系统自动生成..."
                disabled
                v-model="formData.bomCode"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="BOM名称" field="bomName">
              <a-input
                disabled
                v-model="formData.bomName"
                placeholder="请输入产品BOM名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="BOM版本号" field="bomEdition">
              <a-input
                v-model="formData.bomEdition"
                placeholder="请输入产品BOM版本号"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="启用状态" field="state">
              <a-select v-model="formData.state" placeholder="请选择" disabled>
                <a-option
                  v-for="(item, index) in ['启用', '停用']"
                  :key="item"
                  :value="index + 1"
                >
                  {{ item }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div
        class="tab"
        style="margin-top: 20px; display: flex; justify-content: space-between"
      >
        <div>产品工艺路线版本列表</div>
      </div>
      <a-table :pagination="false" :data="groupHistoryList">
        <template #columns>
          <a-table-column
            v-for="header in ProductProcessRouteHerders.herders"
            :key="header.name"
            :width="200"
            :title="header.name"
            align="center"
          >
            <template #cell="{ record }">
              <template v-if="header.name === '状态'">
                <a-typography-text type="danger" v-if="record.state === 1">
                  启用
                </a-typography-text>
                <a-typography-text type="success" v-if="record.state === 2">
                  停用
                </a-typography-text>
              </template>
              <template v-if="header.name === '产品编码'">
                {{ record.management?.number }}
              </template>
              <template v-if="header.name === '产品名称'">
                {{ record.management?.name }}
              </template>
              <template v-if="header.name === '规格型号'">
                {{ record.management?.spec }}
              </template>
              <template v-if="header.name === '基本单位'">
                {{ record.management?.unitData?.name }}
              </template>
              <template v-else>
                {{ record[header.code] }}
              </template>
            </template>
          </a-table-column>
          <a-table-column
            :width="90"
            fixed="right"
            title="启用版本"
            align="center"
          >
            <template #cell="{ record }">
              <a-space>
                <a-switch
                  @click="switchRouteClick(record)"
                  :model-value="record.history"
                  :checked-value="1"
                  :unchecked-value="2"
                />
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <div
        class="tab"
        style="margin-top: 20px; display: flex; justify-content: space-between"
      >
        <div>生产物料配置</div>
      </div>

      <div v-for="item in groupList" :key="item.id" style="margin-bottom: 20px">
        <div
          class="data"
          style="
            margin-bottom: 20px;
            justify-content: space-between;
            display: flex;
            align-items: center;
          "
        >
          <div style="font-size: 20px"> {{ item.name }}</div>
          <a-button
            type="primary"
            @click="
              () => {
                productBomDetailVisible = true;
                choiceId = item.id || 0;
              }
            "
          >
            <template #icon> <icon-plus /> </template>
            添加物料
          </a-button>
        </div>
        <a-table
          :pagination="false"
          :data="groupBomList.filter(({ groupId }) => groupId === item.id)"
        >
          <template #columns>
            <a-table-column
              title="物料编码"
              :width="200"
              data-index="productBomDetail.management.number"
            />
            <a-table-column
              title="物料名称"
              :width="200"
              data-index="productBomDetail.management.name"
            />
            <a-table-column :width="130" data-index="dosage" title="总用量" />
            <a-table-column :width="130" data-index="dosage" title="工序用量">
              <template #cell="{ record }">
                <a-input-number
                  :min="1"
                  :model-value="getValue(record.index, item.id)"
                  @change="setValue($event, record.index, item.id)"
                />
                <a-typography-text
                  :type="
                    getScheduledQuantity(record.bomId) > 0
                      ? 'warning'
                      : getScheduledQuantity(record.bomId) < 0
                      ? 'danger'
                      : 'success'
                  "
                >
                  剩余用量：{{ getScheduledQuantity(record.bomId) }}
                </a-typography-text>
              </template>
            </a-table-column>
            <a-table-column
              title="规格型号"
              :width="200"
              data-index="productBomDetail.management.spec"
            />
            <a-table-column
              title="单位"
              :width="80"
              data-index="productBomDetail.management.unitData.name"
            />

            <a-table-column title="损耗率" :width="130" align="center">
              <template #cell="{ record }">
                {{ record.wastage ? record.wastage + '%' : '' }}
              </template>
            </a-table-column>

            <a-table-column
              :width="110"
              data-index="record.materialProperty"
              title="材料属性"
            />
            <a-table-column :width="80" fixed="right" title="操作">
              <template #cell="{ record }">
                <a-space>
                  <a-link @click="delProduct(record)"> 删除 </a-link>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </a-spin>
  </pageHeader>

  <a-modal
    title="选择关联物料"
    v-model:visible="productBomDetailVisible"
    :width="1000"
  >
    <template #footer>
      <a-button @click="() => (productBomDetailVisible = false)">取消</a-button>
    </template>
    <a-table stripe :pagination="false" :data="formData.productBomDetail">
      <template #columns>
        <a-table-column
          title="物料编码"
          :width="250"
          data-index="productBomDetail.management.number"
        />
        <a-table-column
          title="物料名称"
          :width="250"
          data-index="productBomDetail.management.name"
        />
        <a-table-column
          title="规格型号"
          :width="250"
          data-index="productBomDetail.management.spec"
        />
        <a-table-column
          title="单位"
          :width="250"
          data-index="productBomDetail.management.unitData.name"
        />
        <a-table-column :width="130" data-index="dosage" title="标准用量" />
        <a-table-column :width="130" align="center">
          <template #cell="{ record }">
            {{ record.wastage ? record.wastage + '%' : '' }}
          </template>
        </a-table-column>

        <a-table-column
          :width="130"
          data-index="record.materialProperty"
          title="材料属性"
        />
        <a-table-column :width="80" fixed="right" title="操作">
          <template #cell="{ record }">
            <a-space>
              <a-link @click="addmaterial(record)"> 选择 </a-link>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </a-modal>
</template>

<script setup lang="ts">
  import { reactive, onMounted, ref, computed } from 'vue';
  import { ProductProcessRouteHerders } from '@/utils/tableHerders';
  import {
    GetProductBom,
    EditProductBom,
    EditProductBomHistoryState,
    GetProductBomPage,
    GetProductProcessRoutePage,
    EditProductRoadHistoryState,
  } from '@/api/FactoryModeling';
  import { useRoute, useRouter } from 'vue-router';
  import { TbomBase, TProductBomDetail } from '@/api/FactoryModeling/type';
  import ProductChoice from '@/views/client-side/FactoryModeling/components/ProductChoice.vue';
  import { Message } from '@arco-design/web-vue';

  let route = useRoute();
  let router = useRouter();
  let loading = ref(false);
  let formData = reactive<TbomBase>({});
  let refForm = ref();
  let choiceId = ref(0);

  let getScheduledQuantity = (id: any) => {
    let bomItem = formData.productBomDetail?.find(({ bomId }) => bomId === id);
    console.log(bomItem?.productGroupData);
    return (
      bomItem?.productGroupData?.reduce((num, { dosage }) => {
        return num - (dosage || 0);
      }, bomItem.dosage || 0) || 0
    );
  };

  let getValue = (index: number, id: any) => {
    if (formData.productBomDetail) {
      let productGroupIndex =
        formData.productBomDetail[index].productGroupData?.findIndex(
          ({ productGroupId }) => productGroupId === id
        ) || 0;
      let data = formData.productBomDetail[index].productGroupData;
      if (data) {
        return data[productGroupIndex].dosage;
      }
    }
  };
  let setValue = (val: number | undefined, index: number, id: any) => {
    if (formData.productBomDetail) {
      let productGroupIndex =
        formData.productBomDetail[index].productGroupData?.findIndex(
          ({ productGroupId }) => productGroupId === id
        ) || 0;
      if (formData.productBomDetail[index].productGroupData as any)
        //@ts-ignore
        formData.productBomDetail[index].productGroupData[
          productGroupIndex
        ].dosage = val;
    }
  };

  let handleOk = async () => {
    if (
      !formData.productBomDetail?.every(({ bomId, productBomDetail }) => {
        if (getScheduledQuantity(bomId) === 0) {
          return true;
        } else {
          Message.error(productBomDetail.bomName + '用量未用完或超过总用量');
          return false;
        }
      })
    )
      return;
    try {
      await EditProductBom(formData);
      router.back();
    } catch (err) {
      console.log(err);
    }
  };
  let refProductChoice = ref();
  let productBomDetailVisible = ref(false);

  let groupHistoryList = ref<any[]>([]);
  let groupList = computed<any[]>(
    () =>
      groupHistoryList.value.find(({ history }) => history === 1)?.groupData ||
      []
  );
  let groupBomList = ref<any[]>([]);

  let loadGroupData = () => {
    let list: any[] = [];
    groupList.value.forEach((group) => {
      (
        formData.productBomDetail
          ?.map((item, index1) => ({
            ...item,
            index: index1,
            groupId: group.id,
            productGroupData: item.productGroupData?.map(
              (groupData, index) => ({
                ...groupData,
                index,
              })
            ),
          }))
          ?.filter((item) => {
            console.log(item);
            return item.productGroupData?.some((data) => {
              console.log(group.id, data.productGroupId);
              return group.id === data.productGroupId;
            });
          }) || []
      ).forEach((item) => list.push(item));
    });
    groupBomList.value = list;
  };

  let delProduct = (record: any) => {
    let index: number =
      formData.productBomDetail?.findIndex(
        ({ bomDetailId }) => bomDetailId === record.bomDetailId
      ) || 0;

    if (formData.productBomDetail) {
      let delIndex: number =
        formData.productBomDetail[index].productGroupData?.findIndex(
          ({ productGroupId }) => productGroupId === choiceId.value
        ) || 0;
      formData.productBomDetail[index].productGroupData?.splice(delIndex, 1);
    }
    loadGroupData();
  };

  let addmaterial = (data: TProductBomDetail) => {
    try {
      let index: number =
        formData.productBomDetail?.findIndex(
          ({ bomDetailId }) => bomDetailId === data.bomDetailId
        ) || 0;

      if (!formData.productBomDetail) return;

      let sortIndex = groupList.value.findIndex(
        (item: any) => item.id === choiceId.value
      );
      if (Array.isArray(formData.productBomDetail[index].productGroupData)) {
        if (
          formData.productBomDetail[index].productGroupData?.some(
            ({ productGroupId }) => choiceId.value === productGroupId
          )
        )
          return Message.warning('不可重复添加');
        formData.productBomDetail[index].productGroupData?.push({
          productGroupId: choiceId.value,
          bomDetailId: formData.productBomDetail[index].bomDetailId,
          sortIndex,
        });
      } else {
        formData.productBomDetail[index].productGroupData = [
          {
            productGroupId: choiceId.value,
            bomDetailId: formData.productBomDetail[index].bomDetailId,
            sortIndex,
          },
        ];
      }
      loadGroupData();
      productBomDetailVisible.value = false;
    } catch (err) {
      console.log(err);
    }
  };

  let loadGroupHistoryList = async () => {
    let productProcessRoutePage = await GetProductProcessRoutePage({
      productId: route.query.productId,
      page: 1,
      size: -1,
    });
    groupHistoryList.value = productProcessRoutePage.content || [];
    return Promise.resolve();
  };

  let switchRouteClick = async ({ history, id, productId }: any) => {
    if (history === 1) return Message.error('请通过启用其他历史版本关闭');
    let { state }: any = groupHistoryList.value.map(
      ({ history }: any) => history === 2
    );
    if (state === 2) return Message.error('启用版本正在使用中不可更换');
    await EditProductRoadHistoryState({ id, productId });
    loadGroupHistoryList();
  };
  let productBomList = ref<any[]>([]);
  let loadProductBomList = async () => {
    try {
      let list = await GetProductBomPage({
        page: 1,
        size: -1,
        id: route.query.saveId,
        bomCode: route.query.bomCode,
      });
      productBomList.value = list.content || [];
      let getId = productBomList.value.find(
        ({ historyState }) => historyState === 1
      )?.id;
      let res = await GetProductBom({
        id: getId,
      });
      refProductChoice.value.inputValue = res.management?.name;
      Object.assign(formData, {
        ...res,
        productBomDetail:
          res.productBomDetail.map((item: any) => {
            return {
              ...item,
              wastage: Number(item.wastage),
              id:
                route.query.copyId || route.query.historyId
                  ? undefined
                  : item.id,
              productGroupData: item.productGroupData.filter(
                ({ productGroupId }: any) =>
                  groupList.value.some(({ id }: any) => productGroupId === id)
              ),
            };
          }) || [],
      });
      return Promise.resolve();
    } catch (err) {
      console.log(err);
      return Promise.reject();
    }
  };
  let switchBomClick = async ({ historyState, id, bomCode }: any) => {
    if (historyState === 1) return Message.error('请通过启用其他历史版本关闭');
    await EditProductBomHistoryState({ id, bomCode });
    await loadProductBomList();
    loadGroupData();
  };
  onMounted(async () => {
    loading.value = true;
    try {
      await loadGroupHistoryList();
      await loadProductBomList();
      loadGroupData();
    } catch (err) {
      console.error(err);
    }
    loading.value = false;
  });
</script>

<style scoped lang="less">
  .cantainer {
    padding: 20px;
    width: 100%;
  }

  .bottom {
    border-top: 1px solid var(--color-neutral-4);
    height: 600px;
    .groupData {
      height: 600px;
      overflow-y: hidden;
      border-right: 1px solid var(--color-neutral-4);
      &-item {
        border-bottom: 1px solid var(--color-neutral-4);
        padding: 10px 15px;
        font-size: 16px;
        cursor: pointer;
      }
      &-title {
        font-weight: 550;
        font-size: 18px;
        padding: 10px 15px;
        border-bottom: 1px solid var(--color-neutral-4);
      }
    }
    .choiceList {
      &-title {
        .text {
          font-weight: 550;
          font-size: 18px;
        }
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;
        border-bottom: 1px solid var(--color-neutral-4);
      }
      &-table {
        padding: 15px;
      }
    }
  }
  .form {
    padding-left: 50px;
    padding-right: 50px;
  }

  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
  }

  .tab {
    border-left: 4px rgb(var(--arcoblue-6)) solid;
    padding-left: 20px;
    margin-bottom: 30px;
    font-size: 20px;
  }
</style>
